package net.wwang.blog.service.impl;

import net.wwang.blog.commons.global.ResponseResult;
import net.wwang.blog.dao.CategoryDao;
import net.wwang.blog.pojo.Category;
import net.wwang.blog.service.CategoryService;
import net.wwang.blog.util.IDGenerateUtil;
import net.wwang.blog.util.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author WangWei
 * @date 2020/8/14
 */
@Service
@Transactional
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private IDGenerateUtil IDGenerateUtil;
    @Autowired
    private CategoryDao categoryDao;
    @Override
    public ResponseResult addCategory(Category category) {
        //检查数据
        if (Utils.isEmpty(category.getName())) {
            return ResponseResult.FAILED("分类名称不可以为空");
        }
        if (Utils.isEmpty(category.getSlug())) {
            return ResponseResult.FAILED("分类拼音不能为空");
        }

        if(Utils.isEmpty(category.getDescription())){
            return ResponseResult.FAILED("分类描述不能为空");
        }

        //设置数据
        category.setId(String.valueOf(IDGenerateUtil.nextId()));
        category.setState("1");
        //保存
        categoryDao.save(category);
        return ResponseResult.SUCCESS("添加分类成功");
    }

    @Override
    public ResponseResult getCategoryDetail(String categoryId) {
        Category category = categoryDao.findCategoryById(categoryId);
        if (category == null) {
            return ResponseResult.FAILED("分类不存在");
        }
        return ResponseResult.SUCCESS("分类获取成功").setData(category);
    }

    @Override
    public ResponseResult updateCategory(String categoryId, Category category) {
        Category categoryFromDb = categoryDao.findCategoryById(categoryId);
        if (categoryFromDb == null) {
            return ResponseResult.FAILED("分类不存在");
        }
        String name = category.getName();
        if (!Utils.isEmpty(name)) {
            categoryFromDb.setName(name);
        }
        String slug = category.getSlug();
        if (!Utils.isEmpty(slug)) {
            categoryFromDb.setSlug(slug);
        }
        String description = category.getDescription();
        if (!Utils.isEmpty(description)) {
            categoryFromDb.setDescription(description);
        }
        categoryFromDb.setOrder(category.getOrder());
        categoryDao.save(categoryFromDb);

        return ResponseResult.SUCCESS("分类更新成功");
    }

    @Override
    public ResponseResult deleteCategory(String categoryId) {
        int result = categoryDao.updateState(categoryId);
        if (result == 0) {
            return ResponseResult.FAILED("该分类不存在");
        }
        return ResponseResult.SUCCESS("删除分类成功");
    }
}
